package ace.cmp.data.methodname.sql.mybatisplus.core.inject;

import ace.cmp.data.methodname.sql.mybatisplus.core.factory.MethodNameToSqlMethodFactory;
import ace.cmp.data.methodname.sql.mybatisplus.core.factory.MethodNameToSqlMethodFactoryImpl;
import ace.cmp.data.methodname.sql.mybatisplus.core.properties.MybatisPlugMethodNameToSqlProperties;
import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.injector.AbstractSqlInjector;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import lombok.extern.slf4j.Slf4j;

/**
 * @author caspar
 * @date 2023/2/16 14:13 从方法名，推导sql,并且注入相关sql
 * 推导协议，以spring-data-jdbc为标准
 */
@Slf4j
public class MethodNameToSqlInject extends AbstractSqlInjector {
  private final AbstractSqlInjector defaultSqlInjector;
  private final MethodNameToSqlMethodFactory sqlMethodFactory;
  private final MybatisPlugMethodNameToSqlProperties properties;

  public MethodNameToSqlInject(
      AbstractSqlInjector defaultSqlInjector, MybatisPlugMethodNameToSqlProperties properties) {
    this.defaultSqlInjector = defaultSqlInjector;
    this.properties = properties;
    this.sqlMethodFactory = new MethodNameToSqlMethodFactoryImpl(properties);
  }

  @Override
  public List<AbstractMethod> getMethodList(Class<?> mapperClass, TableInfo tableInfo) {

    List<AbstractMethod> defaultMethodList =
        this.defaultSqlInjector.getMethodList(mapperClass, tableInfo);

    List<AbstractMethod> methodNameToSqlMethodList =
        sqlMethodFactory.getMethods(mapperClass, tableInfo);

    List<AbstractMethod> result =
        Stream.of(defaultMethodList, methodNameToSqlMethodList)
            .flatMap(List::stream)
            .collect(Collectors.toList());

    return result;
  }
}
